import _ from 'underscore';
import Mn from 'backbone.marionette';
import Radio from 'backbone.radio';
import ConfigBus from '../../base/components/ConfigBus.js';
import {
    ajax_call,
    hideLoader,
    showLoader
} from '../../tools';

/** A service to manage attachments for current view context
 *
 * We are not using standard collection-related functions for that, because
 * uploading binary stuff is not very efficient using JSON.
 *
 * Requirements :
 *  - AppOption.context_url is set
 *  - an AjaxFileUploadView is wired on `${AppOption.context_url}/attachments`
 *
 * API (on `facade` radio channel)
 *  - receive `uploadAttachments(file) requests
 *  - triggers `attachment:saved`
 */
const AttachmentUploadServiceClass = Mn.Object.extend({
    channelName: 'facade',
    radioRequests: {
        'uploadAttachment': 'uploadAttachment',
    },
    /**
     * @type {File} the file to be uploaded immediately
     * @return Promise resolving on JSON representation of successfuly
     *   uploaded file.
     */
    uploadAttachment(file) {
        let formData = new FormData();
        formData.append('__formid__', 'deform');
        formData.append('__start__', 'upload:mapping');
        formData.append('upload', file);
        formData.append('__end__', 'upload:mapping');
        formData.append('description', file.name);
        formData.append('submit', 'submit');

        showLoader();
        return ajax_call(
            AppOption['file_upload_url'],
            formData,
            'POST', {
                contentType: false
            } // required for FormData with jQuery
        ).done(function (data) {
            Radio.channel('facade').trigger('attachment:saved', data);
        }).always(hideLoader);
    },
    setup() {
        console.log("AttachmentUploadServiceClass.setup");
    },
    start() {
        console.log("AttachmentUploadServiceClass.start");
        let result = $.Deferred();
        result.resolve(ConfigBus.form_config, null, null);
        return result;
    },
});

const AttachmentUploadService = new AttachmentUploadServiceClass();
export default AttachmentUploadService;